
import { Input } from '@/components/ui/input';
import MenuToggle from '../components/MenuToggle';
import { Badge } from '@/components/ui/badge';
import { CardContent, CardHeader, Card, CardTitle } from '@/components/ui/card';
import { Textarea } from '@/components/ui/textarea';
import { SelectItem, Select, SelectContent, SelectValue, SelectTrigger } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Play, Trash2, Copy, Database, Upload, CheckCircle, Save, AlertCircle, Plus, Code, Download, Settings } from 'lucide-react';
import React, { useState } from 'react';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
const ApiTest = ({ toggleSidebar }) => {
  const [selectedMethod, setSelectedMethod] = useState('GET');
  const [apiUrl, setApiUrl] = useState('');
  const [headers, setHeaders] = useState([{ key: '', value: '' }]);
  const [params, setParams] = useState([{ key: '', value: '' }]);
  const [requestBody, setRequestBody] = useState('');
  const [response, setResponse] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [testHistory, setTestHistory] = useState([]);

  // 预设的API模板
  const apiTemplates = [
    {
      name: '获取用户信息',
      method: 'GET',
      url: '/api/v1/users/12345',
      headers: [
        { key: 'Authorization', value: 'Bearer YOUR_TOKEN' },
        { key: 'Content-Type', value: 'application/json' }
      ]
    },
    {
      name: '创建用户',
      method: 'POST',
      url: '/api/v1/users',
      headers: [
        { key: 'Authorization', value: 'Bearer YOUR_TOKEN' },
        { key: 'Content-Type', value: 'application/json' }
      ],
      body: JSON.stringify({
        name: '张三',
        email: 'zhangsan@example.com',
        password: 'password123'
      }, null, 2)
    },
    {
      name: '上传文件',
      method: 'POST',
      url: '/api/v1/files/upload',
      headers: [
        { key: 'Authorization', value: 'Bearer YOUR_TOKEN' }
      ]
    }
  ];

  const addHeader = () => {
    setHeaders([...headers, { key: '', value: '' }]);
  };

  const updateHeader = (index, field, value) => {
    const newHeaders = [...headers];
    newHeaders[index][field] = value;
    setHeaders(newHeaders);
  };

  const removeHeader = (index) => {
    setHeaders(headers.filter((_, i) => i !== index));
  };

  const addParam = () => {
    setParams([...params, { key: '', value: '' }]);
  };

  const updateParam = (index, field, value) => {
    const newParams = [...params];
    newParams[index][field] = value;
    setParams(newParams);
  };

  const removeParam = (index) => {
    setParams(params.filter((_, i) => i !== index));
  };

  const loadTemplate = (template) => {
    setSelectedMethod(template.method);
    setApiUrl(template.url);
    setHeaders(template.headers || [{ key: '', value: '' }]);
    setRequestBody(template.body || '');
  };

  const sendRequest = async () => {
    setIsLoading(true);
    
    // 模拟API请求
    setTimeout(() => {
      const mockResponse = {
        status: 200,
        statusText: 'OK',
        headers: {
          'Content-Type': 'application/json',
          'X-Response-Time': '120ms'
        },
        data: {
          success: true,
          message: '请求成功',
          data: {
            id: '12345',
            name: '张三',
            email: 'zhangsan@example.com',
            status: 'active',
            createTime: '2024-01-20T10:30:00Z'
          }
        },
        responseTime: 120
      };

      setResponse(mockResponse);
      
      // 添加到历史记录
      const historyItem = {
        id: Date.now(),
        method: selectedMethod,
        url: apiUrl,
        status: mockResponse.status,
        responseTime: mockResponse.responseTime,
        timestamp: new Date().toISOString()
      };
      
      setTestHistory(prev => [historyItem, ...prev.slice(0, 9)]); // 保留最近10条记录
      setIsLoading(false);
    }, 1000);
  };

  const clearRequest = () => {
    setApiUrl('');
    setHeaders([{ key: '', value: '' }]);
    setParams([{ key: '', value: '' }]);
    setRequestBody('');
    setResponse(null);
  };

  const copyResponse = () => {
    if (response) {
      navigator.clipboard.writeText(JSON.stringify(response.data, null, 2));
    }
  };

  const getMethodBadge = (method) => {
    const methodConfig = {
      GET: { color: 'bg-blue-100 text-blue-800' },
      POST: { color: 'bg-green-100 text-green-800' },
      PUT: { color: 'bg-orange-100 text-orange-800' },
      DELETE: { color: 'bg-red-100 text-red-800' }
    };
    
    const config = methodConfig[method] || methodConfig.GET;
    return (
      <Badge className={`${config.color} hover:${config.color} font-mono text-xs`}>
        {method}
      </Badge>
    );
  };

  const getStatusBadge = (status) => {
    if (status >= 200 && status < 300) {
      return <Badge className="bg-green-100 text-green-800">{status}</Badge>;
    } else if (status >= 400) {
      return <Badge className="bg-red-100 text-red-800">{status}</Badge>;
    } else {
      return <Badge className="bg-yellow-100 text-yellow-800">{status}</Badge>;
    }
  };

  return (
    <>
      {/* 头部工具栏 */}
      <div className="mt-3">
        <div className="container mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            {/* 左侧：菜单按钮和标题 */}
            <div className="flex items-center space-x-4">
              <MenuToggle onClick={toggleSidebar} />
              
              <div className="flex items-center space-x-3">
                <div className="w-10 h-10 bg-gradient-to-br from-purple-500 to-purple-600 rounded-xl flex items-center justify-center">
                  <Database className="w-6 h-6 text-white" />
                </div>
                <div>
                  <h1 className="text-2xl font-bold text-material-grey-800">
                    接口测试
                  </h1>
                  <p className="text-sm text-material-grey-600">
                    在线测试和调试API接口
                  </p>
                </div>
              </div>
            </div>

            {/* 右侧：操作按钮 */}
            <div className="flex items-center space-x-3">
              <Button variant="outline" onClick={clearRequest}>
                <Trash2 className="w-4 h-4 mr-2" />
                清空
              </Button>

              <Button variant="outline">
                <Save className="w-4 h-4 mr-2" />
                保存
              </Button>

              <Button variant="outline">
                <Upload className="w-4 h-4 mr-2" />
                导入
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主内容区域 */}
      <div className="flex-1 container mx-auto px-4 py-6">
        <div className="grid grid-cols-1 lg:grid-cols-4 gap-6">
          {/* 左侧：API模板和历史记录 */}
          <div className="lg:col-span-1 space-y-6">
            {/* API模板 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">API模板</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {apiTemplates.map((template, index) => (
                  <button
                    key={index}
                    onClick={() => loadTemplate(template)}
                    className="w-full text-left p-3 rounded-lg border border-material-grey-200 hover:border-primary/50 hover:bg-primary/5 transition-colors"
                  >
                    <div className="flex items-center justify-between mb-1">
                      <span className="font-medium text-sm text-material-grey-900">{template.name}</span>
                      {getMethodBadge(template.method)}
                    </div>
                    <code className="text-xs text-material-grey-600">{template.url}</code>
                  </button>
                ))}
              </CardContent>
            </Card>

            {/* 测试历史 */}
            <Card>
              <CardHeader>
                <CardTitle className="text-lg">测试历史</CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                {testHistory.length > 0 ? (
                  testHistory.map((item) => (
                    <div
                      key={item.id}
                      className="p-3 rounded-lg border border-material-grey-200 hover:bg-material-grey-50 cursor-pointer"
                      onClick={() => {
                        setSelectedMethod(item.method);
                        setApiUrl(item.url);
                      }}
                    >
                      <div className="flex items-center justify-between mb-1">
                        {getMethodBadge(item.method)}
                        {getStatusBadge(item.status)}
                      </div>
                      <code className="text-xs text-material-grey-600 block truncate">{item.url}</code>
                      <div className="text-xs text-material-grey-500 mt-1">
                        {item.responseTime}ms • {new Date(item.timestamp).toLocaleTimeString()}
                      </div>
                    </div>
                  ))
                ) : (
                  <div className="text-center py-6 text-material-grey-500">
                    <Database className="w-8 h-8 mx-auto mb-2 opacity-50" />
                    <p className="text-sm">暂无测试记录</p>
                  </div>
                )}
              </CardContent>
            </Card>
          </div>

          {/* 右侧：请求配置和响应 */}
          <div className="lg:col-span-3 space-y-6">
            {/* 请求配置 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center space-x-2">
                  <Settings className="w-5 h-5" />
                  <span>请求配置</span>
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-4">
                {/* URL和方法 */}
                <div className="flex space-x-3">
                  <Select value={selectedMethod} onValueChange={setSelectedMethod}>
                    <SelectTrigger className="w-32">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="GET">GET</SelectItem>
                      <SelectItem value="POST">POST</SelectItem>
                      <SelectItem value="PUT">PUT</SelectItem>
                      <SelectItem value="DELETE">DELETE</SelectItem>
                      <SelectItem value="PATCH">PATCH</SelectItem>
                    </SelectContent>
                  </Select>
                  
                  <Input
                    placeholder="请输入API地址，例如：/api/v1/users"
                    value={apiUrl}
                    onChange={(e) => setApiUrl(e.target.value)}
                    className="flex-1"
                  />
                  
                  <Button 
                    onClick={sendRequest} 
                    disabled={!apiUrl || isLoading}
                    className="bg-primary hover:bg-primary-600"
                  >
                    {isLoading ? (
                      <>
                        <div className="w-4 h-4 mr-2 border-2 border-white border-t-transparent rounded-full animate-spin" />
                        发送中
                      </>
                    ) : (
                      <>
                        <Play className="w-4 h-4 mr-2" />
                        发送请求
                      </>
                    )}
                  </Button>
                </div>

                {/* 请求详细配置 */}
                <Tabs defaultValue="headers" className="w-full">
                  <TabsList className="grid w-full grid-cols-3">
                    <TabsTrigger value="headers">请求头</TabsTrigger>
                    <TabsTrigger value="params">查询参数</TabsTrigger>
                    <TabsTrigger value="body">请求体</TabsTrigger>
                  </TabsList>

                  <TabsContent value="headers" className="mt-4">
                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <Label>请求头</Label>
                        <Button variant="outline" size="sm" onClick={addHeader}>
                          <Plus className="w-4 h-4 mr-1" />
                          添加
                        </Button>
                      </div>
                      {headers.map((header, index) => (
                        <div key={index} className="flex space-x-2">
                          <Input
                            placeholder="Header名称"
                            value={header.key}
                            onChange={(e) => updateHeader(index, 'key', e.target.value)}
                          />
                          <Input
                            placeholder="Header值"
                            value={header.value}
                            onChange={(e) => updateHeader(index, 'value', e.target.value)}
                          />
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => removeHeader(index)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </TabsContent>

                  <TabsContent value="params" className="mt-4">
                    <div className="space-y-3">
                      <div className="flex items-center justify-between">
                        <Label>查询参数</Label>
                        <Button variant="outline" size="sm" onClick={addParam}>
                          <Plus className="w-4 h-4 mr-1" />
                          添加
                        </Button>
                      </div>
                      {params.map((param, index) => (
                        <div key={index} className="flex space-x-2">
                          <Input
                            placeholder="参数名"
                            value={param.key}
                            onChange={(e) => updateParam(index, 'key', e.target.value)}
                          />
                          <Input
                            placeholder="参数值"
                            value={param.value}
                            onChange={(e) => updateParam(index, 'value', e.target.value)}
                          />
                          <Button
                            variant="ghost"
                            size="icon"
                            onClick={() => removeParam(index)}
                          >
                            <Trash2 className="w-4 h-4" />
                          </Button>
                        </div>
                      ))}
                    </div>
                  </TabsContent>

                  <TabsContent value="body" className="mt-4">
                    <div className="space-y-3">
                      <Label>请求体 (JSON格式)</Label>
                      <Textarea
                        placeholder="请输入JSON格式的请求体"
                        value={requestBody}
                        onChange={(e) => setRequestBody(e.target.value)}
                        rows={8}
                        className="font-mono text-sm"
                      />
                    </div>
                  </TabsContent>
                </Tabs>
              </CardContent>
            </Card>

            {/* 响应结果 */}
            {response && (
              <Card>
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="flex items-center space-x-2">
                      <Code className="w-5 h-5" />
                      <span>响应结果</span>
                    </CardTitle>
                    <div className="flex items-center space-x-2">
                      <Button variant="outline" size="sm" onClick={copyResponse}>
                        <Copy className="w-4 h-4 mr-1" />
                        复制
                      </Button>
                      <Button variant="outline" size="sm">
                        <Download className="w-4 h-4 mr-1" />
                        下载
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <Tabs defaultValue="response" className="w-full">
                    <TabsList className="grid w-full grid-cols-2">
                      <TabsTrigger value="response">响应体</TabsTrigger>
                      <TabsTrigger value="headers">响应头</TabsTrigger>
                    </TabsList>

                    <TabsContent value="response" className="mt-4">
                      <div className="space-y-3">
                        {/* 状态信息 */}
                        <div className="flex items-center space-x-4 p-3 bg-material-grey-50 rounded-lg">
                          <div className="flex items-center space-x-2">
                            <span className="text-sm text-material-grey-600">状态:</span>
                            {getStatusBadge(response.status)}
                          </div>
                          <div className="flex items-center space-x-2">
                            <span className="text-sm text-material-grey-600">响应时间:</span>
                            <Badge variant="secondary">{response.responseTime}ms</Badge>
                          </div>
                          <div className="flex items-center space-x-2">
                            {response.status >= 200 && response.status < 300 ? (
                              <CheckCircle className="w-4 h-4 text-green-600" />
                            ) : (
                              <AlertCircle className="w-4 h-4 text-red-600" />
                            )}
                            <span className="text-sm text-material-grey-600">{response.statusText}</span>
                          </div>
                        </div>

                        {/* 响应数据 */}
                        <div className="bg-material-grey-900 text-white p-4 rounded-lg">
                          <pre className="text-sm overflow-x-auto">
                            <code>{JSON.stringify(response.data, null, 2)}</code>
                          </pre>
                        </div>
                      </div>
                    </TabsContent>

                    <TabsContent value="headers" className="mt-4">
                      <div className="space-y-2">
                        {Object.entries(response.headers).map(([key, value]) => (
                          <div key={key} className="flex items-center space-x-3 p-2 bg-material-grey-50 rounded">
                            <code className="text-sm font-medium text-blue-600">{key}:</code>
                            <code className="text-sm text-material-grey-700">{value}</code>
                          </div>
                        ))}
                      </div>
                    </TabsContent>
                  </Tabs>
                </CardContent>
              </Card>
            )}

            {/* 空状态 */}
            {!response && (
              <Card>
                <CardContent className="py-12">
                  <div className="text-center">
                    <div className="w-24 h-24 mx-auto mb-4 bg-material-grey-200 rounded-full flex items-center justify-center">
                      <Database className="w-8 h-8 text-material-grey-500" />
                    </div>
                    <h3 className="text-lg font-medium text-material-grey-700 mb-2">
                      等待发送请求
                    </h3>
                    <p className="text-material-grey-500">
                      配置请求参数后点击"发送请求"按钮开始测试
                    </p>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </div>
      </div>
    </>
  );
};

export default ApiTest;
